<template>
  <div>
    <el-card shadow="never">
      <template #header>
        <h3>题库批量导入</h3>
      </template>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleTabClick">
        <el-tab-pane v-for="item in tabList" :label="item.label" :name="item.name">
          <div class="action-bar" v-if="item.name === '0' || item.name === '1'">
            <el-upload class="upload-component" :action="excelServer" :headers="headers" :show-file-list="false"
              :on-success="handleImportSuccess" :on-error="handleImportError" :before-upload="beforeImportUpload"
              :disabled="uploadLoading">
              <el-button type="primary" :loading="uploadLoading">
                <el-icon>
                  <Upload />
                </el-icon>
                {{ item.name === '0' ? '导入题库' : '导入课程' }}
              </el-button>
            </el-upload>
            <el-button v-ripple @click="handleDownloadTemplate(Number(item.name) + 1)" :loading="downloadLoading">
              <el-icon>
                <Download />
              </el-icon>
              {{ item.name === '0' ? '下载题库模板' : '下载课程模板' }}
            </el-button>
          </div>
          <div class="action-bar" v-else>
            <!-- handleSyncQuestion(1) -->
            <el-button v-ripple type="primary" @click="dialogVisible = true" :loading="syncLoading">
              <el-icon>
                <Refresh />
              </el-icon>
              同步题库到驾校
            </el-button>
            <!-- <el-button v-ripple @click="handleSyncQuestion(2)" :loading="syncLoading">
              <el-icon>
                <Refresh />
              </el-icon>
              同步课程到驾校
            </el-button> -->
          </div>
          <art-table :data="tableData" v-loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize"
            :total="pageTotal" @current-change="handleCurrentChange" @size-change="handleSizeChange"
            :empty-text="emptyText">
            <template #default>
              <el-table-column type="selection" width="55" />
              <el-table-column label="ID" prop="id" width="150" />
              <el-table-column label="导入记录" prop="detailInfo" />
              <el-table-column label="导入时间" prop="startTime" />
              <el-table-column label="状态" prop="status">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)" size="small">
                    {{ buildTagText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
            </template>
          </art-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog v-model="dialogVisible" title="同步类型" width="500" body-class="sync-body">
      <el-alert title="首次同步请选择“同步题库全部信息”" type="primary" style="margin-bottom: 20px;" />
      <el-form>
        <el-form-item label="类型：">
          <el-select v-model="syncType" placeholder="请选择同步类型" style="width:250px;">
            <el-option label="同步题库全部信息" value="03" />
            <el-option label="仅同步题库基础信息" value="01" />
            <el-option label="仅同步题库速学速记" value="02" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="performSync(1)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import type { TabsPaneContext } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, Download, Refresh } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/modules/user'
import { downQuestionExcel, asyncQuestion, operationRecords } from '@/api/questionbank'

const dialogVisible = ref(false)
const syncType = ref('')
const tabList = [
  { label: '题库导入记录', name: '0' },
  // { label: '课程导入记录', name: '1' },
  { label: '同步记录', name: '2' }
]
// 类型定义
interface TableItem {
  ID: string
  importRecords: string
  importTime: string
  status: string
  startTime?: string
  endTime?: string
}

interface ImportResponse {
  code: string
  msg: string
  data?: any
}

// 常量定义
const EXCEL_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
const MAX_FILE_SIZE = 50 * 1024 * 1024 // 50MB

// 用户状态
const userStore = useUserStore()
const { accessToken } = userStore

// API配置
const server = `${import.meta.env.VITE_API_URL}files`
const excelServer = `${import.meta.env.VITE_API_URL}ds-question/importXlsx`
const headers = { Authorization: `Bearer ${accessToken}`, store_id: localStorage.getItem('lty-store-id') }

// 响应式数据
const activeName = ref<string>('0')
const tableData = ref<TableItem[]>([
  {
    ID: "1",
    importRecords: '已导入300道题',
    importTime: '2025-01-05 10:30:00',
    status: '成功'
  }
])

// 加载状态
const tableLoading = ref(false)
const uploadLoading = ref(false)
const downloadLoading = ref(false)
const syncLoading = ref(false)

// 分页数据
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)

// 计算属性
const emptyText = computed(() => {
  const tabLabels: Record<string, string> = {
    '0': '暂无题库导入记录',
    '1': '暂无课程导入记录',
    '2': '暂无同步记录'
  }
  return tabLabels[activeName.value] || '暂无数据'
})

// 方法定义
const loadTableData = async () => {
  try {
    tableLoading.value = true
    // 这里应该调用实际的API接口
    console.log(activeName.value, "activeName.value===");
    const operationContent = activeName.value === '0' ? 0 : activeName.value === '1' ? 1 : null
    const res = await operationRecords({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      storeId: 0,
      operationType: activeName.value === '0' || activeName.value === '1' ? 0 : 1,
      operationContent
    })
    if (res.code === '00000') {
      tableData.value = res.data.list
      pageTotal.value = res.data.total
    }

    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500))
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败，请稍后重试')
  } finally {
    tableLoading.value = false
  }
}

const handleTabClick = (e: any) => {
  // 切换标签时重置分页
  pageNum.value = 1
  // 这里可以根据标签加载不同的数据
  loadTableData()
}

const handleCurrentChange = (val: number) => {
  pageNum.value = val
  loadTableData()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  loadTableData()
}

const getStatusType = (status: string): 'success' | 'danger' | 'info' => {
  const statusMap: Record<string, 'success' | 'danger' | 'info'> = {
    '成功': 'success',
    '失败': 'danger',
    '进行中': 'info'
  }
  return statusMap[status]
}
const buildTagText = (status: number) => {
  let text = ''
  if (status === 0) {
    text = '进行中'
  } else if (status === 1) {
    text = '成功'
  } else if (status === 2) {
    text = '失败'
  }
  return text
}

// const handleSyncQuestion = async (type: number) => {
//   const typeText = type === 1 ? '题库' : '课程'

//   try {
//     await ElMessageBox.confirm(
//       `确定将所有${typeText}都同步到驾校吗？`,
//       `同步${typeText}`,
//       {
//         confirmButtonText: '确定',
//         cancelButtonText: '取消',
//         type: 'warning'
//       }
//     )

//     await performSync(type)
//   } catch (error) {
//     if (error !== 'cancel') {
//       console.error('同步失败:', error)
//       ElMessage.error('同步失败，请稍后重试')
//     }
//   }
// }

const performSync = async (type: number) => {
  try {
    syncLoading.value = true
    const res = await asyncQuestion({ state: type, type: syncType.value })

    if (res && res.code === '00000') {
      ElMessage.success(res.msg || '同步成功')
      loadTableData() // 刷新数据
      dialogVisible.value = false
    } else {
      ElMessage.error(res?.msg || '同步失败')
    }
  } catch (error) {
    console.error('同步请求失败:', error)
    ElMessage.error('同步失败，请稍后重试')
  } finally {
    syncLoading.value = false
  }
}

const beforeImportUpload = (file: File): boolean => {
  const isExcel = file.type === EXCEL_MIME_TYPE
  const isLt50 = file.size < MAX_FILE_SIZE

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!')
    return false
  }

  if (!isLt50) {
    ElMessage.error('文件大小不能超过50MB!')
    return false
  }

  uploadLoading.value = true
  return true
}

const handleImportSuccess = (response: ImportResponse) => {
  uploadLoading.value = false

  if (response.code === '00000') {
    ElMessage.success('导入成功')
    loadTableData() // 刷新数据
  } else {
    ElMessage.error(response.msg || '导入失败')
  }
}

const handleImportError = (error: any) => {
  uploadLoading.value = false
  console.error('导入失败:', error)
  ElMessage.error('导入失败，请稍后重试')
}

const handleDownloadTemplate = async (type: number) => {
  try {
    downloadLoading.value = true

    const res = await downQuestionExcel({ categoryId: type })

    if (res instanceof Blob) {
      // 创建下载链接
      const link = document.createElement('a')
      link.href = URL.createObjectURL(res)
      link.download = type === 1 ? '题库导入模板.xlsx' : '视频课程导入模板.xlsx'
      link.style.display = 'none'
      document.body.appendChild(link)
      link.click()

      // 清理
      URL.revokeObjectURL(link.href)
      document.body.removeChild(link)

      ElMessage.success('模板下载成功')
    } else {
      ElMessage.error('下载失败')
    }
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('下载失败，请稍后重试')
  } finally {
    downloadLoading.value = false
  }
}

// 初始化
onMounted(() => {
  loadTableData()
})
</script>

<style lang="scss" scoped>
.action-bar {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin: 20px 0;

  .upload-component {
    display: inline-block;
  }
}

:deep(.el-tabs__content) {
  padding-top: 0;
}

:deep(.el-table) {
  margin-top: 16px;
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

:deep(.el-tag) {
  font-weight: 500;
}

:deep(.sync-body) {
  padding: 0 0 25px !important;
}
</style>